package org.ciallo.easytokendemo.controller;

import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.codec.binary.Base64;
import org.ciallo.easytokencore.annotation.EasyCheckLogin;
import org.ciallo.easytokencore.annotation.EasyTokenAutoRefresh;
import org.ciallo.easytokencore.annotation.EasyTokenAutoInject;
import org.ciallo.easytokencore.context.EasyContext;
import org.ciallo.easytokencore.context.EasyContextHolder;
import org.ciallo.easytokencore.error.EasyErrorCode;
import org.ciallo.easytokencore.exception.EasyLoginException;
import org.ciallo.easytokendemo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
*@Description: 
*@Author: Jukomu
*@Package: org.ciallo.easytokendemo.demo.controller
*@Project: easy-token-demo
*@name: UserController
*@Date: 2025-05-16
*@Filename: UserController
*/
@RestController
@RequestMapping("user")
@RequiredArgsConstructor(onConstructor_=@Autowired)
public class UserController {
    private final IUserService iUserService;

    @RequestMapping("login")
    @EasyTokenAutoInject
    public String login(@RequestParam("uuid") String uuid, @RequestParam("name") String name, @RequestParam("password") String password) throws NoSuchAlgorithmException {
        // 验证密码
        MessageDigest digest = MessageDigest.getInstance("MD5");
        String encoded = Base64.encodeBase64String(digest.digest(password.getBytes()));
        boolean verifyUser = iUserService.verifyUser(uuid, encoded);
        if (verifyUser) {
            EasyContext context = EasyContextHolder.getContext();
            EasyContextHolder.getToken().addPayload("uuid", uuid);
            EasyContextHolder.getToken().addPayload("name", name);
            return "OK";
        }
        throw new EasyLoginException(EasyErrorCode.CODE_LOGIN_FAILED, "登录失败");
    }

    @RequestMapping("test1")
    @EasyCheckLogin
    @EasyTokenAutoRefresh
    @ResponseBody
    public String testAnnotation() {
        return "OK";
    }
}
